package org.jeecg.modules.paycenter.channel.pufa;

import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.paycenter.enums.BillTypeEnum;
import org.jeecg.modules.paycenter.enums.PayChannelEnum;
import org.jeecg.modules.paycenter.enums.PaySourceEnum;
import org.jeecg.modules.paycenter.dto.PayBillData;
import org.jeecg.modules.paycenter.service.BasePayChannelService;
import org.jeecg.modules.paycenter.service.IPayChannelService;
import org.jeecg.modules.wlhy.bill.entity.HyBill;
import org.jeecg.modules.wlhy.bill.entity.HyCarrierBill;
import org.jeecg.modules.wlhy.bill.entity.HyCustomerBill;
import org.jeecg.modules.wlhy.bill.entity.HyShippingNoteBill;
import org.jeecg.modules.wlhy.company.entity.HyCompany;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.hycarrier.entity.HyCarrier;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hypfaccount.entity.HyPfAccount;
import org.jeecg.modules.wlhy.hypfaccount.service.IHyPfAccountService;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class PfPayChannelService extends BasePayChannelService implements IPayChannelService {
    public static  final String CHANNEL = PayChannelEnum.PF.channelType;

    @Autowired private IHyPfAccountService hyPfAccountService;
    @Autowired private PfBankUtil pfBankUtil;
    @Autowired private PfBankService pfBankService;

    //region base
    @Override
    public PayChannelEnum getChannelEnum() {
        return PayChannelEnum.PF;
    }

    @Override
    public String getChannel() {
        return PayChannelEnum.PF.channelType;
    }

    @Override
    public boolean checkChannel() {
        HyConfig config = HyConfigUtils.getConfig();
        return config.getPfIzUse();
    }
    //endregion

    //region  电子回单
    @Override
    public Result<?> batchDownloadCustomerBilHd(List<HyCustomerBill> customerBills){
        String customerId = customerBills.get(0).getCustomerId();
        //货主钱包
        HyPfAccount customerAccount = hyPfAccountService.getCustomerAccount(customerId);
        if (customerAccount == null) {
            return Result.error("货主钱包信息不存在");
        }
        //交易席位号
        String bidsSnglFlgCd = customerAccount.getBidsSnglFlgCd();
        List<HyCustomerBill> failBills = new ArrayList<>();
        for (HyCustomerBill bill : customerBills) {
            if (!CHANNEL.equals(bill.getPayChannel())) {
                continue;
            }
            if (!StringUtils.isEmpty(bill.getBankHdFu())) {
                continue;
            }
            //查询回单
            try {
                pfBankUtil.downloadCustomerBillHd(bill, bidsSnglFlgCd);
//                Result<?> ret = pfBankUtil.downloadCustomerBillHd(bill, bidsSnglFlgCd);
//                if (!ret.isSuccess()) {
//                    return ret;
//                }
            } catch (Exception ex) {
                ex.printStackTrace();
                failBills.add(bill);
            }
        }
        if(failBills.size() > 0) {
            return Result.OK(String.format("下载完成,失败{}条",failBills.size()));
        }
        return Result.OK("下载完成");
    }

    @Override
    public Result<?> batchDownloadShippingBillHd(List<HyShippingNoteBill> shippingNoteBills) {

        String companyId = shippingNoteBills.get(0).getCompanyId();
        for (HyShippingNoteBill bill : shippingNoteBills) {
            if (!StringUtils.equals(companyId, bill.getCompanyId())) {
                return Result.error("所选数据不是同一个公司,不能下载");
            }
        }
        //货主钱包
        HyPfAccount companyAccount = hyPfAccountService.getCompanyAccount(companyId);
        if (companyAccount == null) {
            return Result.error("货主钱包信息不存在");
        }
        //交易席位号
        String bidsSnglFlgCd = companyAccount.getBidsSnglFlgCd();
        List<HyShippingNoteBill> failBills = new ArrayList<>();
        for (HyShippingNoteBill hyShippingNoteBill : shippingNoteBills) {
            if (!CHANNEL.equals(hyShippingNoteBill.getPayChannel())) {
                continue;
            }
            if (hyShippingNoteBill.getBankHd() != null) {
                continue;
            }
            //查询回单
            try {
                pfBankUtil.downloadCompanyBillHd(hyShippingNoteBill , bidsSnglFlgCd);
//                Result<?> ret = pfBankUtil.downloadCompanyBillHd(hyShippingNoteBill , bidsSnglFlgCd);
//                if (!ret.isSuccess()) {
//                    return ret;
//                }
            } catch (Exception ex) {
//                return Result.error(ex.getMessage());
                failBills.add(hyShippingNoteBill);
                ex.printStackTrace();
            }
        }
        if(failBills.size() > 0) {
            return Result.OK(String.format("下载完成,失败{}条",failBills.size()));
        }
        return Result.OK("下载完成");
    }
    //endregion

    //region 支付

    @Override
    public Result<?> billPayBatch(List<HyBill> hyBills, HyCustomer customer) {
        HyPfAccount customerAccountBook = hyPfAccountService.getCustomerAccount(customer.getId());
        if (customerAccountBook == null) {
            return Result.error("货主尚未开通钱包功能!");
        }
        //检查货主运费是否够支付
        BigDecimal availBal = pfBankUtil.getChildAccountBal(customerAccountBook.getChildAcctNo());
        if (availBal == null) {
            return Result.error("查询余额失败");
        }
        //获取总支付运费
        BigDecimal totalAmt = billService.getBillCustomerTotalFee(hyBills);
        if (totalAmt.compareTo(availBal) > 0) {
            return Result.error("余额不足");
        }
        List<HyShippingNote> hyShippingNotes = billService.getBillShippingList(hyBills);
        Map<String, HyDriver> driverMaps = billService.getDriverMaps(hyShippingNotes); //司机
        Map<String, HyVehicle> vehicleMaps = billService.getVehicleMaps(hyShippingNotes);//车辆
        Map<String, HyCarrier> carrierMaps = billService.getCarrierMaps(hyShippingNotes);//车队长
        Map<String, HyCompany> companyMaps = billService.getCompanyMaps(hyShippingNotes);

        //检查，获取司机，车辆，车队长信息
        Result<?> driverRet = pfBankService.getDriverAccounts(driverMaps);
        if (!driverRet.isSuccess()) {
            return driverRet;
        }
        Map<String, HyPfAccount> driverAccountBookMaps = (Map<String, HyPfAccount>) driverRet.getResult();
        Map<String, HyPfAccount> carrierAccountBookHashMaps = pfBankService.getCarrierAccounts(carrierMaps);
        Map<String, HyPfAccount> companyAccountBookMaps = pfBankService.getCompanyAccounts(companyMaps);

        Map<String, HyShippingNote> shippingNoteMap = billService.shippingListToMap(hyShippingNotes);

        for (HyBill hyBill : hyBills) {
            hyBill.setPaySource(PaySourceEnum.ACCOUNT_PAY.value);//支付源为货主账户余额
        }
        List<PayBillData> payDatas = billService.createBillPayDatas(this.getChannel(), hyBills, shippingNoteMap, driverMaps, vehicleMaps);
        //设置支付账户信息
        pfBankService.setBillPayDatasAccInfo(payDatas, customerAccountBook, companyAccountBookMaps, driverAccountBookMaps, carrierAccountBookHashMaps);
        billService.saveBillPayDatas(hyBills, payDatas);
        this.billPayBatch(hyBills);
        return Result.OK("申请支付成功");
    }

    @Override
    public Result<?> billPlateformPay(List<HyBill> hyBills, HyCustomer customer) {
        return Result.error("操作不可用,不支持此功能");
    }

    @Override
    public Result<?> billRePayBatch(List<HyBill> hyBills, HyCustomer customer) {
        List<PayBillData> payDatas = billService.getBillRePayDatas(hyBills);
        for (PayBillData payData : payDatas) {
            HyCustomerBill customerBill = payData.getCustomerBill();
            String customerBillRespSource = customerBill.getRespSource();
            if("-1".equals(customerBillRespSource) ||"-2".equals(customerBillRespSource)){
                throw new JeecgBootException("包含支付状态不确定运单，需人工处理");
            }

            HyShippingNoteBill shippingNoteBill = payData.getShippingNoteBill();
            String shippingNoteBillRespSource = shippingNoteBill.getRespSource();
            if("-1".equals(shippingNoteBillRespSource) ||"-2".equals(shippingNoteBillRespSource)){
                throw new JeecgBootException("包含支付状态不确定运单，需人工处理");
            }
            HyBill hyBill = payData.getHyBill();
            if("1".equals(hyBill.getIzCarrierPay())) {
                HyCarrierBill carrierBill = payData.getCarrierBill();
                String carrierBillRespSource = carrierBill.getRespSource();
                if ("-1".equals(carrierBillRespSource) || "-2".equals(carrierBillRespSource)) {
                    throw new JeecgBootException("包含支付状态不确定运单，需人工处理");
                }
            }
        }
        pfBankService.setBillRePayDatas(payDatas);
        this.billPayBatch(hyBills);
        return Result.OK("申请支付成功");
    }

    @Override
    public Result<?> agentDianFuPayBatch(BillTypeEnum billTypeEnum, List<HyBill> hyBills, HyCustomer agent, HyCustomer customer) {
        return Result.error("操作不可用,不支持此功能");
    }

    //endregion

}
